using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Admin.NET.Application.Service.Electricity;
using Admin.NET.Application.Service.Electricity.Dto;
using Admin.NET.Core;
using Furion.DependencyInjection;
using Furion.EventBus;
using Microsoft.Extensions.DependencyInjection;

namespace Admin.NET.Application.EventBus;

public class PaySubscribe : IEventSubscriber, ISingleton, IPrivateDependency
{
	private readonly IServiceProvider _serviceProvider;

	public PaySubscribe(IServiceProvider serviceProvider)
	{
		_serviceProvider = serviceProvider;
	}

	/// <summary>
	/// 合闸
	/// </summary>
	/// <param name="context"></param>
	/// <returns></returns>
	[EventSubscribe("SwitchOnGate")]
	public async Task SwitchOnGate(EventHandlerExecutingContext context)
	{
		using IServiceScope scope = _serviceProvider.CreateScope();
		SqlSugarRepository<ElectricMeter> _rep = scope.ServiceProvider.GetRequiredService<SqlSugarRepository<ElectricMeter>>();
		EventPayload payload = (EventPayload)context.Source.Payload;
		long roomId = long.Parse(payload.Data);
		List<ElectricMeter> meters = await (from f in _rep.AsQueryable()
			where f.RoomId == (long?)roomId && f.TenantId == (long?)payload.TenantId
			select f).ToListAsync();
		if (meters.Count <= 0)
		{
			return;
		}
		foreach (ElectricMeter item in meters)
		{
			if (item.GateStatus == 0)
			{
				ElectricityService electricityService = scope.ServiceProvider.GetRequiredService<ElectricityService>();
				InputSwitch input = new InputSwitch
				{
					Id = item.Id,
					GateStatus = 0
				};
				await electricityService.SwitchMeter(input, payload.TenantId);
			}
		}
	}
}
